import os
import sys
import re
import subprocess
import pandas as pd
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel, QFileDialog, QTextBrowser, QSplitter, QDesktopWidget,  QHBoxLayout, QLineEdit, QCheckBox
from PyQt5.QtGui import QFont
import openpyxl

class MergeCsvApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('课表自动生成工具v1.0')
        self.setGeometry(100, 100, 400, 200)
        self.setStyleSheet(
            "QMainWindow { background-color: #f0f0f0; }"
            "QWidget { font-family: '微软雅黑'; }"
        )
        font = QFont()
        font.setPointSize(14)
        self.setFont(font)

        self.mainWidget = QWidget()
        self.setCentralWidget(self.mainWidget)

        self.mainLayout = QVBoxLayout()
        self.mainWidget.setLayout(self.mainLayout)

        # 获取屏幕的几何信息
        screen_geometry = QDesktopWidget().screenGeometry()
        # 计算窗口的位置使其居中
        window_width = self.frameGeometry().width()
        window_height = self.frameGeometry().height()
        x = (screen_geometry.width() - window_width) / 2
        y = (screen_geometry.height() - window_height) / 2
        self.move(int(x), int(y))

        # 编写左侧代码UI
        self.maininfoLabel = QLabel('CSV文件批量合并工具',  self)
        self.maininfoLabel.setStyleSheet('color: #7171C6; font-size: 18px; font-weight: bold;')
        self.mainLayout.addWidget(self.maininfoLabel)

        # 添加一个读取文件夹中所有文件的按钮
        self.openFolderButton = QPushButton('打开csv文件存放目录', self)
        self.openFolderButton.clicked.connect(self.openCsvFolder)
        self.mainLayout.addWidget(self.openFolderButton)

        # 添加一个打开文件保存目录的一个按钮
        self.openFolderButton = QPushButton('打开文件保存目录', self)
        self.openFolderButton.clicked.connect(self.openSaveFolder)
        self.mainLayout.addWidget(self.openFolderButton)

        # 添加一个启动按钮
        self.startButton = QPushButton('启动', self)
        self.startButton.clicked.connect(self.mianStartExtraction)
        self.mainLayout.addWidget(self.startButton)

        # ResultTextEdit
        self.mainResultTextEdit = QTextBrowser(self)
        self.mainResultTextEdit.setOpenExternalLinks(True)
        self.mainLayout.addWidget(self.mainResultTextEdit)

    # 编写open_floder函数
    def openCsvFolder(self):
        # 打开文件夹
        folder_path = QFileDialog.getExistingDirectory(self)
        if folder_path:
            self.open_folder_path = folder_path
            self.mainResultTextEdit.append(f'已选择的CSV文件存放文件夹: {self.open_folder_path}')

    def openSaveFolder(self):
        # 打开文件夹
        folder_path = QFileDialog.getExistingDirectory(self)
        if folder_path:
            self.save_folder_path = folder_path
            self.mainResultTextEdit.append(f'已选择的结果保存文件夹: {self.save_folder_path}')
    def mianStartExtraction(self):
        # if hasattr(self, 'pptFilePath', 'wordFilePath'):
        if hasattr(self, 'open_folder_path') and hasattr(self, 'save_folder_path'):
            self.mainResultTextEdit.append('\n文件处理中...')
            folder_path = CsvUtil(self.open_folder_path, self.save_folder_path).mergeCsv()
            # self.rightResultTextEdit.append(f'\n输出文件夹: <a href="file:///{folder_path}">{folder_path}</a>')
            self.mainResultTextEdit.append(f'\n输出文件: {folder_path}')
        # 打开文件夹
            subprocess.Popen(['explorer', os.path.abspath(os.path.dirname(folder_path))], shell=True)  # Windows 上使用 "explorer"
        else:
            self.mainResultTextEdit.append('\n请先选择一个PPT文件。')

class CsvUtil:
    def __init__(self, origin_folder_path, result_folder_path):
        self.origin_folder_path = origin_folder_path
        self.result_folder_path = result_folder_path
        # self.csv_files = [file for file in os.listdir(origin_folder_path) if file.endswith('.csv')]

    def mergeCsv(self):
        csv_files = [file for file in os.listdir(self.origin_folder_path) if file.endswith('.csv')]
        merged_data = pd.read_csv(os.path.join(self.origin_folder_path, csv_files[0]))

        for file in csv_files[1:]:
            file_path = os.path.join(self.origin_folder_path, file)
            data_to_append = pd.read_csv(file_path)
            merged_data = pd.concat([merged_data, data_to_append], ignore_index=True)
        # 提取合并后的文件名，这里使用 csv_files[0]中的文件名
        merged_file_name = csv_files[0].split('.')[0] + '_merged'
        output_file = os.path.join(self.result_folder_path, merged_file_name+ ".csv")
        merged_data.to_csv(output_file, index=False)
        return output_file

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MergeCsvApp()
    mainWindow.show()
    sys.exit(app.exec_())
